package com.lz.library.extension

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.pm.PackageInfo
import android.graphics.Point
import android.os.Process
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.view.WindowManager
import com.lz.library.base.BaseApp
import java.net.NetworkInterface
import java.util.*

/**
 *  author: you : 2020/10/27
 */

//全局context
val APP: Context by lazy { BaseApp.context }

/**
 * 获取手机im值
 * @return
 */
fun Context.getTerminalId(): String {
    val imei = getDeviceId(this)
    return if (TextUtils.isEmpty(imei)) netMacAddress() else imei
}

@SuppressLint("MissingPermission")
fun getDeviceId(context: Context): String {
    return try {
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val imei = if (hasO()) tm.imei else tm.deviceId
        if (TextUtils.isEmpty(imei)) Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) else imei
    } catch (e: Exception) {
        ""
    }
}

fun netMacAddress(): String {
    try {
        val nis = NetworkInterface.getNetworkInterfaces()
        while (nis.hasMoreElements()) {
            val ni = nis.nextElement()
            if (ni.name == "wlan0" || ni.name == "eth0") {
                val ha = ni.hardwareAddress
                if (ha != null && ha.isNotEmpty()) {
                    val buf = StringBuilder()
                    ha.forEach { buf.append(String.format("%02X:", it)) }
                    if (buf.isNotEmpty()) buf.deleteCharAt(buf.length - 1)
                    return buf.toString().lowercase(Locale.getDefault())
                }
            }
        }
    } catch (_: Exception) {
    }
    return ""
}

/**
 * @param packageName
 * @return
 */
fun Context.getPackageInfo(packageName: String): PackageInfo? {
    return try {
        packageManager.getPackageInfo(packageName, 0)
    } catch (e: Exception) {
        null
    }
}

fun Context.getCurrentProcessName(): String {
    if (hasP()) return Application.getProcessName()
    var processName = try {
        Class.forName("android.app.ActivityThread").getMethod("currentProcessName").invoke(null) as String
    } catch (e: Exception) {
        null
    }
    if (!TextUtils.isEmpty(processName)) return processName!!
    val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val pid = Process.myPid()
    am.runningAppProcesses?.forEach { if (it.pid == pid) return it.processName }
    return ""
}

fun Context.getScreenPoint(): Point {
    val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    if (hasR()) return wm.currentWindowMetrics.bounds.run { Point(width(), height()) }
    return Point().apply { wm.defaultDisplay.getRealSize(this) }
}